package com.juyu.miliao.scheduler.message;

import com.juyu.miliao.common.constant.OfficialQuestionInfoRedisKey;
import com.juyu.miliao.common.constant.OfficialQuestionRabbitMqInfo;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.Set;

/**
 * @author xuanqicheng
 * @create 2018-24-09:47
 */
@Component
public class OfficialQuestionInfoMessage {
    private final Logger logger = LoggerFactory.getLogger("questionAndAnswerLog");
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 跟新官方问题缓存缓存
     *
     * @param message
     */
    @RabbitListener(bindings = @QueueBinding(value = @Queue(OfficialQuestionRabbitMqInfo.QUEUE_TO_OFFICIAL_QUESTION_ID_QUEUE),
            exchange = @Exchange(OfficialQuestionRabbitMqInfo.EXCHANGE_TO_OFFICIAL_QUESTION),
            key = {OfficialQuestionRabbitMqInfo.ROUTING_KEY_TO_UPDATE_OFFICIAL_QUESTION}))
    public void getUpdateQuestion(String message) {
        try {
            if (!StringUtils.isEmpty(message)) {

                Set<String> deletKeySet = new HashSet<>();

                String newOfficialQuestionKey = OfficialQuestionInfoRedisKey.NEW_OFFICIAL_QUESTION_INFO;

                deletKeySet.add(newOfficialQuestionKey);

                logger.info("[更新官方问题缓存]根据官方问题ID:{},获取最新问题缓存key={}", message, newOfficialQuestionKey);

                String officialQuestionPagerKey = OfficialQuestionInfoRedisKey.OFFICIAL_QUESTION_PAGE_INFO + "*";

                Set<String> officialQuestionPageInfoSet = stringRedisTemplate.keys(officialQuestionPagerKey);

                if (officialQuestionPageInfoSet != null && officialQuestionPageInfoSet.size() > 0) {

                    deletKeySet.addAll(officialQuestionPageInfoSet);

                    logger.info("[更新官方问题缓存]根据官方问题ID:{},获取分页缓存key:{}个", message, officialQuestionPageInfoSet.size());
                }

                String officialQuestionByIdKey = OfficialQuestionInfoRedisKey.OFFICIAL_QUESTION_INFO_BY_QUESTIONID + message;


                deletKeySet.add(officialQuestionByIdKey);

                logger.info("[更新官方问题缓存]根据官方问题ID:{},获取官方问题缓存key={}",message,officialQuestionByIdKey);

                stringRedisTemplate.delete(deletKeySet);

                logger.info("[更新官方问题缓存]根据官方问题ID:{},删除了key:{}个", message, deletKeySet.size());
            }

        } catch (Exception ex) {
            logger.error("[更新官方问题缓存]错误:" + ex.getMessage());
        }
    }
}
